<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>工单信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      <el-form label-position="left" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工单编号">
              <span>{{ workOrderInfo.workOrderCode || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工单名称">
              <span>{{ workOrderInfo.workOrderName || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联计划">
              <span>{{ workOrderInfo.planName || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品名称">
              <span>{{ workOrderInfo.productName || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编号">
              <span>{{ workOrderInfo.productCode || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格型号">
              <span>{{ workOrderInfo.productSfn || workOrderInfo.specification || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="计划数量">
              <span>{{ workOrderInfo.qtyNum || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际生产数量">
              <span>{{ workOrderInfo.actualQty || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位">
              <span>{{ workOrderInfo.productUnit || workOrderInfo.unit || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="计划开始时间">
              <span>{{ workOrderInfo.planStartTime || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划结束时间">
              <span>{{ workOrderInfo.planEndTime || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-tag :type="workOrderInfo.statusType || 'info'">{{ workOrderInfo.statusLabel || '未知状态' }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="实际开始时间">
              <span>{{ workOrderInfo.actualStartTime || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际结束时间">
              <span>{{ workOrderInfo.actualEndTime || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="来源单号">
              <span>{{ workOrderInfo.sourceDocNo || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>工序任务列表</span>
      </div>
      <el-table v-loading="loading" :data="taskList" style="width: 100%">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="工序编号" prop="processCode" align="center" width="120" />
        <el-table-column label="工序名称" prop="processName" align="center" width="120" />
        <el-table-column label="工位" prop="stationName" align="center" width="120" />
        <el-table-column label="计划数量" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.plannedQty }}
          </template>
        </el-table-column>
        <el-table-column label="已完成数量" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.completedQty || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="合格数量" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.qualifiedQty || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="不合格数量" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.unqualifiedQty || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="getTaskStatusType(scope.row.status)">{{ scope.row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === '0'"
              size="mini"
              type="info"
              @click="dispatchTask(scope.row)"
            >派工</el-button>
            <el-button
              v-if="scope.row.status === '1'"
              size="mini"
              type="primary"
              @click="startTask(scope.row)"
            >开始</el-button>
            <el-button
              v-if="scope.row.status === '2'"
              size="mini"
              type="success"
              @click="completeTask(scope.row)"
            >完成</el-button>
            <el-button
              v-if="scope.row.status === '2'"
              size="mini"
              type="warning"
              @click="pauseTask(scope.row)"
            >暂停</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;" v-if="taskList && taskList.length > 0">
      <div slot="header" class="clearfix">
        <span>生产进度图</span>
      </div>
      <div class="progress-timeline">
        <div v-for="(process, index) in productionProgress" :key="index" class="task-progress">
          <div class="task-info">
            <div class="task-name">{{ process.processName }}</div>
            <div class="task-status">{{ process.status }}</div>
          </div>
          <el-progress
            :percentage="process.percentage"
            :stroke-width="20"
          ></el-progress>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getWorkOrder } from "@/api/sc/workOrder";
import { startWorkOrderTask, completeWorkOrderTask, pauseWorkOrderTask } from "@/api/sc/workOrderTask";
import { formatDate } from "@/utils/index";

export default {
  name: "WorkOrderDetail",
  data() {
    return {
      // 工单ID
      workOrderId: undefined,
      // 工单信息
      workOrderInfo: {},
      // 工序任务列表
      taskList: [],
      // 状态映射
      statusMap: {
        '0': { type: 'info', label: '待排产' },
        '1': { type: 'info', label: '未开始' },
        '2': { type: 'primary', label: '进行中' },
        '3': { type: 'success', label: '已完成' },
        '4': { type: 'warning', label: '已暂停' },
        '5': { type: 'warning', label: '待质检' },
        '6': { type: 'danger', label: '已取消' }
      },
      loading: true
    };
  },
  computed: {
    productionProgress() {
      if (!this.taskList || this.taskList.length === 0) {
        return [];
      }

      // 1. 按工序名称分组
      const processGroups = this.taskList.reduce((groups, task) => {
        const key = task.processName || '未命名工序';
        if (!groups[key]) {
          groups[key] = {
            processName: key,
            tasks: []
          };
        }
        groups[key].tasks.push(task);
        return groups;
      }, {});

      // 2. 计算每个工序分组的进度和状态
      const progressData = Object.values(processGroups).map(group => {
        const totalPlanned = group.tasks.reduce((sum, task) => {
          const qty = parseFloat(task.plannedQty || task.qtyNum);
          return sum + (isNaN(qty) ? 0 : qty);
        }, 0);

        const totalCompleted = group.tasks.reduce((sum, task) => {
          const qty = parseFloat(task.completedQty);
          return sum + (isNaN(qty) ? 0 : qty);
        }, 0);

        const percentage = totalPlanned > 0 ? Math.round((totalCompleted / totalPlanned) * 100) : 0;

        // 3. 决定综合状态
        let statusText = '未知状态';
        if (group.tasks.some(t => t.status === '2' || t.status === '进行中')) {
            statusText = '进行中';
        } else if (group.tasks.some(t => t.status === '5' || t.status === '待质检')) {
            statusText = '待质检';
        } else if (group.tasks.every(t => t.status === '3' || t.status === '已完成')) {
            statusText = '已完成';
        } else if (group.tasks.every(t => t.status === '1' || t.status === '已派工' || t.status === '0' || t.status === '未开始' || t.status === '待排产')) {
            statusText = '未开始';
        } else if (group.tasks.some(t => t.status === '4' || t.status === '已暂停')) {
            statusText = '已暂停';
        } else {
            // 默认使用第一个任务的状态名作为代表
            statusText = group.tasks[0].statusName || '未知状态';
        }

        return {
          processName: group.processName,
          percentage: percentage,
          status: statusText,
          // 将原始任务也附加上，以备将来扩展
          tasks: group.tasks
        };
      });

      return progressData;
    }
  },
  watch: {
    '$route'(to, from) {
      if (to.query.workOrderId) {
        this.workOrderId = to.query.workOrderId;
        console.log('工单详情页面路由变化，刷新数据');
        this.getWorkOrderInfo();
      }
    },
    // 监听工单ID变化
    workOrderId(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        console.log('工单ID变化，刷新详情数据');
        this.getWorkOrderInfo();
      }
    }
  },
  created() {
    this.workOrderId = this.$route.query.workOrderId;
    this.getWorkOrderInfo();
  },
  methods: {
    // 获取工单信息
    getWorkOrderInfo() {
      this.loading = true;
      getWorkOrder(this.workOrderId).then(response => {
        console.log('API返回数据:', response);
        
        // 处理嵌套数据结构，工单信息在workOrder属性中
        if (response.data && response.data.workOrder) {
          this.workOrderInfo = response.data.workOrder;
        } else {
          this.workOrderInfo = response.data || {};
        }
        
        // 处理状态显示
        const statusInfo = this.statusMap[this.workOrderInfo.status] || { type: 'info', label: '未知状态' };
        this.workOrderInfo.statusType = statusInfo.type;
        this.workOrderInfo.statusLabel = statusInfo.label;
        
        // 处理工序任务列表，任务列表在taskList属性中
        if (response.data && response.data.taskList) {
          this.taskList = response.data.taskList;
        } else if (this.workOrderInfo.workOrderTasks) {
          this.taskList = this.workOrderInfo.workOrderTasks;
        } else {
          console.log('工序任务列表不存在，使用空数组');
          this.taskList = [];
        }
        
        console.log('处理后工单信息:', this.workOrderInfo);
        console.log('处理后任务列表:', this.taskList);
        
        this.loading = false;
      }).catch(error => {
        console.error('获取工单详情失败:', error);
        this.loading = false;
      });
    },
    
    // 返回上级页面
    goBack() {
      this.$router.go(-1);
    },
    
    // 获取任务状态类型
    getTaskStatusType(status) {
      const statusTypes = {
        '0': 'info',     // 未开始
        '1': 'warning',  // 已派工
        '2': 'primary',  // 进行中
        '3': 'success',  // 已完成
        '4': 'warning',  // 已暂停
        '5': 'warning'   // 待质检
      };
      return statusTypes[status] || 'info';
    },
    
    // 计算任务进度百分比
    getTaskProgressPercentage(task) {
      // 优先根据实际完成数量计算进度
      if (task.qtyNum && task.qtyNum > 0) {
        const completedQty = task.completedQty || 0;
        const plannedQty = task.qtyNum;
        
        // 如果有实际完成数量，使用实际进度
        if (completedQty > 0) {
          const percentage = Math.floor((completedQty / plannedQty) * 100);
          return Math.min(percentage, 100);
        }
        
        // 如果没有实际完成数量，但有状态变化，显示虚拟进度
        // 这样可以提供视觉反馈，同时不影响实际业务逻辑
        if (task.status === '1') return 5;   // 已派工：显示5%虚拟进度
        if (task.status === '2') return 15;  // 进行中：显示15%虚拟进度
        if (task.status === '3') return 100; // 已完成：显示100%
        if (task.status === '4') return 0;   // 已暂停：显示0%
        if (task.status === '5') return 95;  // 待质检：显示95%
      }

      // 如果没有数量信息，根据状态返回默认进度
      if (task.status === '0') return 0;        // 未开始
      if (task.status === '1') return 5;        // 已派工但未开工，显示虚拟进度5%
      if (task.status === '2') return 15;       // 进行中，显示虚拟进度15%
      if (task.status === '3') return 100;      // 已完成
      if (task.status === '4') return 0;        // 已暂停
      if (task.status === '5') return 95;       // 待质检

      return 0;
    },
    
    // 获取任务进度状态
    getTaskProgressStatus(task) {
      const statusMap = {
        '0': '',        // 未开始
        '1': 'warning', // 已派工
        '2': 'primary', // 进行中
        '3': 'success', // 已完成
        '4': 'warning', // 已暂停
        '5': 'warning'  // 待质检
      };
      return statusMap[task.status] || '';
    },

    // 派工任务
    dispatchTask(task) {
      const taskId = task.workOrderTaskId;
      if (!taskId) {
        this.$modal.msgError("任务ID不能为空");
        return;
      }

      // 跳转到派工页面
      this.$router.push({
        path: '/sc/task/dispatch',
        query: {
          id: taskId,
          t: new Date().getTime()
        }
      });
    },

    // 开始任务
    startTask(task) {
      console.log('开始任务被调用，任务信息:', task);
      const taskId = task.workOrderTaskId;
      console.log('任务ID:', taskId);
      if (!taskId) {
        this.$modal.msgError("任务ID不能为空");
        return;
      }

      this.$modal.confirm('确认要开工此工序任务吗？').then(() => {
        startWorkOrderTask(taskId).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("任务开工成功");
            this.getWorkOrderInfo(); // 刷新数据
          } else {
            this.$modal.msgError(response.msg || "任务开工失败");
          }
        }).catch(error => {
          console.error("开工任务失败:", error);
          this.$modal.msgError("操作失败，请稍后重试");
        });
      }).catch(() => {});
    },
    
    // 完成任务
    completeTask(task) {
      const taskId = task.workOrderTaskId;
      if (!taskId) {
        this.$modal.msgError("任务ID不能为空");
        return;
      }

      this.$modal.confirm('确认要完成此工序任务吗？').then(() => {
        completeWorkOrderTask(taskId).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("任务完成成功");
            this.getWorkOrderInfo(); // 刷新数据
          } else {
            this.$modal.msgError(response.msg || "任务完成失败");
          }
        }).catch(() => {
          this.$modal.msgError("操作失败，请稍后重试");
        });
      }).catch(() => {});
    },

    // 暂停任务
    pauseTask(task) {
      const taskId = task.workOrderTaskId;
      if (!taskId) {
        this.$modal.msgError("任务ID不能为空");
        return;
      }

      this.$modal.confirm('确认要暂停此工序任务吗？').then(() => {
        pauseWorkOrderTask(taskId).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("任务暂停成功");
            this.getWorkOrderInfo(); // 刷新数据
          } else {
            this.$modal.msgError(response.msg || "任务暂停失败");
          }
        }).catch(() => {
          this.$modal.msgError("操作失败，请稍后重试");
        });
      }).catch(() => {});
    },
    /** 格式化日期时间 */
    formatDate(cellValue) {
      return formatDate(cellValue);
    }
  }
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.progress-timeline {
  padding: 20px 0;
}

.task-progress {
  margin-bottom: 20px;
}

.task-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.task-name {
  font-weight: bold;
}

.task-status {
  color: #606266;
}
</style> 